package com.link.base.base.purchaseplan.service;


import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.purchaseplan.dao.mybatis.mapper.PurchasePlanMapper;
import com.link.base.base.purchaseplan.model.PurchasePlan;
import com.link.base.base.purchaseplan.model.PurchasePlanItem;
import com.link.base.base.system.model.Period;
import com.link.base.base.system.service.PeriodService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.query.Filter;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.*;
import java.util.Arrays;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 要货计划实现类
 *
 * @author NingLanhao
 * @date 2018-11-21 12:05
 */
@Service
public class PurchasePlanServiceImpl extends BasicServiceImpl<PurchasePlan> implements PurchasePlanService {

    @Resource
    private PurchasePlanMapper purchasePlanMapper;

    @Resource
    private PurchasePlanItemService purchasePlanItemService;

    @Resource
    private AccountService accountService;

    @Resource
    private PeriodService periodService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BasicMapper<PurchasePlan> getBasicMapper() {
        return purchasePlanMapper;
    }

    /**
     * 【新建】状态值列表
     */
    private static final String PURCHASE_PLAN_STATUS_NEW = "NEW";
    /**
     * 【撤回】状态值列表
     */
    private static final String PURCHASE_PLAN_STATUS_WITHDRAWN = "Withdrawn";

    /**
     * 【提交】状态值列表
     */
    private static final String PURCHASE_PLAN_STATUS_SUBMIT = "Submitted";
    /**
     * 【提交】状态值列表
     */
    private static final String PURCHASE_PLAN_STATUS_CANCELLED = "Cancelled";

    /**
     * 【经销商员工】员工类型值列表
     */
    private static final String EMP_TYPE_DEALER = "DealerEmployee";

    /**
     * mybatis筛选可以编辑状态标识
     */
    public static final String EDIT_STATUS = "editStatus";


    @Override
    public void beforInsert(PurchasePlan entity) throws Exception {
        /**
         * 【经销商客户id】不能为空
         */
        CoreUser user = UserUtil.getUser();
        String empType = user.getEmpType();
        Long userAcctId = user.getAcctId();
        if (Objects.equals(EMP_TYPE_DEALER, empType)) {
            entity.setAccountId(userAcctId);
            entity.setAcctOrgId(user.getOrgId());
        }
        Long accountId = entity.getAccountId();
        boolean accountIdCheck = (accountId == null);
        if (accountIdCheck) {
            throw new ServiceException("PURCHASE-004");
        }

        /**
         * 【经销商客户组织id】不能为空
         */
        Long acctOrgId = entity.getAcctOrgId();
        boolean acctOrgIdCheck = (acctOrgId == null);
        if (acctOrgIdCheck) {
            throw new ServiceException("PURCHASE-005");
        }

        /**
         * 【期间ID】不能为空
         */
        Long periodId = entity.getPeriodId();
        boolean periodIdCheck = (periodId == null);
        if (periodIdCheck) {
            throw new ServiceException("PURCHASE-006");
        }

        /**
         * 【状态】不能为空且新建状态为【NEW】
         */
        String status = entity.getStatus();
        boolean statusCheck = StringValidateUtils.isNull(status);
        if (statusCheck) {
            throw new ServiceException("PUBLIC-008");
        }
        if (!Objects.equals(status, PURCHASE_PLAN_STATUS_NEW)) {
            throw new ServiceException("PURCHASE-007");
        }

        /**
         * 【计划单编号】订单编号生成规则
         */
        String planOrderNum = keyGenerateService.keyGenerate().toString();
        entity.setPlanOrderNum(planOrderNum);

        /***
         * 校验经销商是否已存在当前期间的要货计划（不包括 “提交” 状态）
         */
        PurchasePlan record = new PurchasePlan();
        record.setAccountId(entity.getAccountId());
        record.setPeriodId(entity.getPeriodId());
        record.setAttr1(EDIT_STATUS);
        List<PurchasePlan> purchasePlanList = purchasePlanMapper.queryByExamplePage(record);
        if (purchasePlanList != null && purchasePlanList.size() > 0) {
            throw new ServiceException("PURCHASE-008");
        }

    }

    @Override
    public void beforUpdate(PurchasePlan entity) throws Exception {
        /***
         * 校验经销商是否已存在当前期间的要货计划（不包括 “提交” 状态）
         */
        PurchasePlan record = new PurchasePlan();
        record.setAccountId(entity.getAccountId());
        record.setPeriodId(entity.getPeriodId());
        record.setAttr1(EDIT_STATUS);
        List<PurchasePlan> purchasePlanList = purchasePlanMapper.queryByExamplePage(record);
        if (purchasePlanList != null && purchasePlanList.size() > 0) {
            if (purchasePlanList.size() == 1) {
                PurchasePlan purchasePlan = purchasePlanList.get(0);
                if (!Objects.equals(entity.getId(), purchasePlan.getId())) {
                    throw new ServiceException("PURCHASE-008");
                }
            } else {
                throw new ServiceException("PURCHASE-008");
            }
        }
        super.beforUpdate(entity);
    }

    /**
     * 更新要货计划头对象状态
     *
     * @param entity 要货计划对象
     * @return void
     * @author Wei Xuan
     * @created 15:25 2018/11/23
     */
    @Override
    public void updateStatus(PurchasePlan entity) {
        try {
            /**
             * 【提交时间】默认为当前时间
             */
            String status = entity.getStatus();
            if (Objects.equals(PURCHASE_PLAN_STATUS_SUBMIT, status)) {
                PurchasePlanItem item = new PurchasePlanItem();
                item.setHeadId(entity.getId());
                List<PurchasePlanItem> purchasePlanItems = purchasePlanItemService.queryByExamplePage(item);
                if (purchasePlanItems == null || purchasePlanItems.size() < 1) {
                    throw new ServiceException("PURCHASE-009");
                }
                Date now = new Date();
                String submitDate = DateUtil.dateToStr(now, DateUtil.DATE_TIME);
                entity.setSubmitDate(submitDate);
            } else {
                entity.setSubmitDate(null);
            }
            purchasePlanMapper.statusUpdate(entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 根据经销商ID、期间ID校验是否已存在当前数据
     *
     * @param entity
     * @return 要货计划头对象
     * @author Wei Xuan
     * @created 20:10 2018/11/28
     */
    @Override
    public PurchasePlan queryRepeatOne(PurchasePlan entity) {
        PurchasePlan purchasePlan = new PurchasePlan();
        try {
            String accountNum = entity.getAccountNum();
            if (StringUtils.isBlank(accountNum)) {
                return entity;
            }
            String periodName = entity.getPeriodName();
            if (StringUtils.isBlank(periodName)) {
                return entity;
            }
            // 选择该经销商下该期间的计划单，过滤掉已取消状态的计划单
            String []statusFilter = {PURCHASE_PLAN_STATUS_WITHDRAWN,PURCHASE_PLAN_STATUS_NEW};
            PurchasePlan record = (PurchasePlan) QueryParamUtil.addQpsFilter(PurchasePlan.class,
                    new Filter("periodName", periodName),
                    new Filter("accountNum", accountNum),
                    new Filter("status", Filter.OP_IN, Arrays.asList(statusFilter))
            );
            List<PurchasePlan> purchasePlanList = purchasePlanMapper.queryByExamplePage(record);
            if (purchasePlanList != null && purchasePlanList.size() > 0) {
                purchasePlan = purchasePlanList.get(0);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
        return purchasePlan;
    }

    /**
     * 导入创建要货计划头
     *
     * @param entity
     * @return void
     * @author Wei Xuan
     * @created 20:26 2018/11/28
     */
    @Override
    public void createPurchasePlan(PurchasePlan entity) throws ServiceException {
        try {
            String accountNum = entity.getAccountNum();
            String periodName = entity.getPeriodName();
            if (StringUtils.isBlank(accountNum)) {
                throw new ServiceException("PURCHASE-010");
            }
            if (StringUtils.isBlank(periodName)) {
                throw new ServiceException("PURCHASE-011");
            }
            Account acctEntity = new Account();
            acctEntity.setAcctCode(accountNum);
            List<Account> accountList = accountService.queryByExamplePage(acctEntity);
            if (accountList != null && accountList.size() > 0) {
                entity.setAccountId(accountList.get(0).getId());
            }
            Period periodEntity = new Period();
            periodEntity.setTitle(periodName);
            List<Period> periodList = periodService.queryByExamplePage(periodEntity);
            if (periodList != null && periodList.size() > 0) {
                entity.setPeriodId(periodList.get(0).getId());
            }
            this.insert(entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }


}

